﻿using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        //public IHubProxy HubProxy { get; set; }
        //const string ServerUri = "http://localhost:5205/signalr";
        const string ServerUri = "http://121.89.194.47:5205/signalr";
        public HubConnection Connection { get; set; }

        public Form1()
        {
            InitializeComponent();
            this.FormClosed += Form1_FormClosed;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            Connection.DisposeAsync();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ConnectAsync();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            var str = string.IsNullOrEmpty(TextBoxMessage.Text) ? "bbb" : TextBoxMessage.Text;

            // 通过代理来调用服务端的Send方法
            // 服务端Send方法再调用客户端的AddMessage方法将消息输出到消息框中
            Connection.SendAsync("SendMessage","aa", new RobotState { Name=str,WorkingState = RobotWorkingState.充电中 } );

            //RichTextBoxConsole.Text = String.Empty;
            //RichTextBoxConsole.Focus();
        }

        private async void ConnectAsync()
        {
            try
            {
                Connection = new HubConnectionBuilder()
                    .WithUrl(ServerUri).WithAutomaticReconnect().Build();
                Connection.On<string>("ShowMsg", s =>
                {
                    this.Invoke(new Action(() =>
                    {
                        RichTextBoxConsole.AppendText($" {s}{Environment.NewLine}");
                    }));
                });
                Connection.On<RobotState>("ShowInfo", s =>
                {
                    this.Invoke(new Action(() =>
                    {
                        RichTextBoxConsole.AppendText($" {s.WorkingState}{Environment.NewLine}");
                    }));
                });
                Connection.Closed += Connection_Closed;
                Connection.ServerTimeout = TimeSpan.FromSeconds(60);
                Connection.KeepAliveInterval = TimeSpan.FromSeconds(0);
                await Connection.StartAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            #region MyRegion

            // Connection = new HubConnection(ServerUri);
            //Connection.Closed += Connection_Closed; 

            //// 创建一个集线器代理对象
            //HubProxy = Connection.CreateHubProxy("SignalRHub");

            //// 供服务端调用，将消息输出到消息列表框中
            //HubProxy.On<string, string>("SendMessage", (name, message) =>
            //     this.Invoke(new Action(() =>
            //        RichTextBoxConsole.AppendText(String.Format("{0}: {1}\r", name, message))
            //    )));

            //try
            //{
            //    await Connection.Start();
            //}
            //catch (HttpRequestException)
            //{
            //    // 连接失败
            //    return;
            //}

            // 显示聊天控件
            //ChatPanel.Visibility = Visibility.Visible;
            //button1.Enabled = true;
            //RichTextBoxConsole.Focus();
            //RichTextBoxConsole.AppendText("连上服务：" + ServerUri + "\r");
            #endregion
        }

        private System.Threading.Tasks.Task Connection_Closed(Exception arg)
        {
            //等待3s后重新创建连接
            Task.Delay(3 * 1000).ContinueWith(s=>  
                Connection.StartAsync()
            );
            //Something
            return null;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Form1 form = new Form1();
            form.Text = "form2";
            form.Show();
        }

        private void btnAddG_Click(object sender, EventArgs e)
        {
            Connection.SendAsync("SendStatement", "aa");
            return;
        }
    }
}
